<template>
    <div class="LW_return_div">
        <div class="LW_return_body">
            <div class="LW_return_header">
                <div class="LW_return_header_ico">
                    <a-icon type="check-circle" style="font-size: 10vw;color: springgreen;" theme="filled"/>
                </div>
                <div class="LW_return_header_text">
                    照片上传
                </div>

            </div>
            <div class="LW_return_content">
                是否继续拍摄照片？
            </div>
            <div class="LW_return_footer">
                <div class="LW_return_cancel">
                    <a-button class="LW_return_cancel_button" @click="continuePhoto()">继续拍摄</a-button>
                </div>
                <div class="LW_return_ok">
                    <a-button class="LW_return_ok_button" type="primary" @click="nextStep()">下一步</a-button>
                </div>
            </div>
        </div>
    </div>
</template>
<style >
    .LW_return_div{
        width: 100vw;
        height: 100vh;
        padding: 50vw 0 0 0;
        generic-family: PingFangSC-Semibold;
        background: rgb(237,237,237);
    }
    .LW_return_body{
        width: 94vw;
        height: 70vw;
        margin:0 3vw 0 3vw ;
        border: solid 0.3vw grey;
        border-radius: 2vw;
        padding: 5vw 0 5vw 0;
    }
    .LW_return_header{
        width: 94vw;
        height: 12vw;
        border-bottom: 0.3vw dashed grey;

    }
    .LW_return_content{
        width: 94vw;
        height: 30vw;
        line-height: 30vw;
        padding: 0 0 0 17vw;
        font-size: 8vw;
        text-align: left;
    }

    .LW_return_header_ico{
        width: 15vw;
        line-height: 12vw;
        height: 12vw;
        float: left;
        text-align: right;
        padding: 1vw 0 0 0;
    }
    .LW_return_header_text{
        width: 75vw;
        line-height: 12vw;
        height: 12vw;
        font-size: 6vw;
        color: black;
        float: left;
        text-align: left;
        font-weight: 600;
        padding: 0 0 0 2vw;
    }
    .LW_return_footer{
        width: 94vw;
        height: 18vw;
        border-top: 0.2vw dashed grey;
        padding-top:2vw ;
    }
    .LW_return_cancel{
        width: 47vw;
        height: 18vw;
        line-height: 18vw;
        float: left;
        padding-left: 5vw;

    }
    .LW_return_ok{
        width: 47vw;
        height: 18vw;
        float: left;
        line-height: 18vw;
        padding-right: 5vw;
    }
    .LW_return_cancel_button{
        width: 30vw;
        height: 15vw;
        border: #00b7ff 0.3vw solid;
    }
    .LW_return_ok_button{
        width: 30vw;
        height: 15vw;
    }


</style>
<script>
    import axios from 'axios'
    export default {
        name: "LineWorkSurePhoto",
        data() {
            return {
               /* myStep:'8',*/
                lineWorkUrl:'',
                id:'',
                step:'',
                name:'',
                latitude:localStorage.getItem("latitude")?localStorage.getItem("latitude"):"",
                longitude:localStorage.getItem("longitude")?localStorage.getItem("longitude"):"",
                sid:localStorage.getItem("sid"),
                workModeId:localStorage.getItem("workModeId"),
                myPhotoInfo:{},
                reportHistory:localStorage.getItem("reportHistory")?JSON.parse(localStorage.getItem("reportHistory")):[],
                Authorization:localStorage.getItem("userToken"),
            }
        },
        mounted(){
            this.init();
        },
        methods:{
            init(){
                //初始化路由参数：当前步骤名称等
                this.step = this.$route.params.step?this.$route.params.step:JSON.parse(localStorage.getItem("currStepInfo")).step;
                this.id = this.$route.params.id?this.$route.params.id:JSON.parse(localStorage.getItem("currStepInfo")).id;
                this.name = this.$route.params.name?this.$route.params.name:JSON.parse(localStorage.getItem("currStepInfo")).name;
                if(typeof (this.$route.params.lineWorkUrl) !=="undefined"){
                    this.lineWorkUrl = this.$route.params.lineWorkUrl;
                    console.log('lineWorkSurePhoto!==undefined');
                }else{
                    let n = parseInt(this.step);
                    switch(n)
                    {
                        //这里的n代表下一步的路由
                        case 1:
                            this.lineWorkUrl = 'lineWorkSurePerson';
                            break;
                        case 2:
                            this.lineWorkUrl = 'lineWorkSureTool';
                            break
                        case 3:
                            this.lineWorkUrl = 'lineWorkInto';
                            break;
                        case 4:
                            this.lineWorkUrl = 'lineWorkBegin';
                            break;
                        case 5:
                            this.lineWorkUrl = 'lineWorkEnd';//结束作业
                            break;
                        case 6:
                            this.lineWorkUrl = 'lineWorkOut';//跳过7作业工单,到8作业出场
                            break;
                        case 8:
                            this.lineWorkUrl = 'lineWorkSureOutTool';//9确认料具出
                            break;
                        case 9:
                            this.lineWorkUrl = 'lineWorkReturn';
                            break;
                        default:
                            this.lineWorkUrl = 'lineWork';
                            break;

                        //这里的step:n代表上一步传到这里的，可n+1往后理解一个路由步骤
                        /*case 1:
                            this.lineWorkUrl = 'lineWorkSurePlan';
                            break;
                        case 2:
                            this.lineWorkUrl = 'lineWorkSurePerson';
                            break;
                        case 3:
                            this.lineWorkUrl = 'lineWorkSureTool';
                            break
                        case 4:
                            this.lineWorkUrl = 'lineWorkInto';
                            break;
                        case 5:
                            this.lineWorkUrl = 'lineWorkBegin';
                            break;
                        case 6:
                            this.lineWorkUrl = 'lineWorkEnd';
                            break;
                        //缺少7作业工单忽略跳过
                        case 8:
                            this.lineWorkUrl = 'lineWorkOut';
                            break;
                        case 9:
                            this.lineWorkUrl = 'lineWorkSureOutTool';
                            break;
                        default:
                            this.lineWorkUrl = 'lineWork';
                            break;*/
                    }

                }
                console.log(" step:"+this.step + " id:"+this.id + " name:"+this.name+" lineWorkUrl:"+this.lineWorkUrl);
            },
            nextStep(){
                console.log("click nextStep")
                this.$router.push({name:this.lineWorkUrl,params: {step:this.step,id:this.id}});
            },
            continuePhoto(){
                let me = this;
                let cameraOptions= {
                    quality : 100,
                    destinationType : Camera.DestinationType.DATA_URL,
                    sourceType : Camera.PictureSourceType.CAMERA,     //照相机类型
                    allowEdit : false,
                    encodingType : Camera.EncodingType.JPEG,
                    /*targetWidth : 100,
                    targetHeight : 100,*/
                    SaveToPhotoAlburn:true,//捕获后将图像保存到设备上的相册中。
                    popoverOptions : CameraPopoverOptions,
                    saveToPhotoAlbum : true,
                    correctOrientation: true,
                };
                console.log("继续拍摄调用拍照接口");
                navigator.camera.getPicture(this.onCameraSuccess,this.onCameraError,cameraOptions);
            },
            onCameraSuccess(imageURL){
                let nowTime = new Date();//得到当前拍摄时间
                this.sendStep(imageURL,nowTime);
                this.addTaskToast();
                /*this.sendPhoto(imageURL,nowTime);*/

            },
            onCameraError(e){
                console.log("onCameraError:" + e);
            },
            sendPhoto(imageURL,nowTime) {
                let formData = new FormData();

                let getBlob = this.convertBase64UrlToBlob(imageURL);
                let file = this.blobToFile(getBlob);
                this.fileName = this.getFileTime(nowTime)+".jpg";
                this.createTime = this.getFormatTimeLine(nowTime);

                formData.append("file",file,this.fileName);
                formData.append('WorkStep',this.name);
                formData.append('WorkPlanId',this.id);
                formData.append('userId',this.sid);
                formData.append('workModeId',this.workModeId);
                formData.append("longitude",this.longitude);
                formData.append("latitude",this.latitude);
                formData.append("time",this.createTime);
                /*formData.append("file",this.convertBase64UrlToBlob(imageURL));*/

                console.log(file);
                console.log(formData.get('file'));
                let configs = {
                    headers: {
                        "Content-Type":'multipart/form-data',
                        "Authorization":this.Authorization,
                    }
                    /* ,timeout:3000*/
                };
                axios.post('http://'+localStorage.getItem("apiHost")+'/app/work/upload',formData,configs).then(res=>{
                    if(res.status === 200){
                        this.myPhotoInfo.fileName = this.fileName;
                        this.myPhotoInfo.createTime = this.createTime;
                        this.myPhotoInfo.sid = this.sid;
                        this.reportHistory.push(this.myPhotoInfo);
                        this.myPhotoInfo.isOk = "1";
                        localStorage.setItem("reportHistory",JSON.stringify(this.reportHistory));//保存进内存
                        console.log("照片上传成功");

                    }
                }).catch((error) =>{
                    console.log("照片信息提交失败");
                    console.log(error);
                    this.myPhotoInfo.fileName = this.fileName;
                    this.myPhotoInfo.createTime = this.createTime;
                    this.myPhotoInfo.sid = this.sid;
                    this.reportHistory.push(this.myPhotoInfo);
                    this.myPhotoInfo.isOk = "0";
                    localStorage.setItem("reportHistory",JSON.stringify(this.reportHistory));//保存进内存

                })
            },

            convertBase64UrlToBlob(imageURI) {
                let bytes = window.atob(imageURI); //去掉url的头，并转换为byte
                //处理异常,将ascii码小于0的转换为大于0
                let ab = new ArrayBuffer(bytes.length);
                let ia = new Uint8Array(ab);
                for(let i = 0; i < bytes.length; i++) {
                    ia[i] = bytes.charCodeAt(i);
                }
                return new Blob([ab], { type: 'image/jpeg' });
            },
            blobToFile(theBlob,fileName) {
                //将blob转换为file
                theBlob.lastModifiedDate = new Date();
                theBlob.name = fileName;
                return theBlob;
            },
            getFileTime(nowTime){
                let year = nowTime.getFullYear();
                let mouth = nowTime.getMonth() + 1;
                let day =nowTime.getDate();
                let hour = nowTime.getHours();
                let minutes = nowTime.getMinutes();
                let seconds= nowTime.getSeconds();

                //将时分秒转化为双位数
                let mouth1 =setNum(mouth);
                let day1 =setNum(day);
                let h1 = setNum(hour);
                let m1 = setNum(minutes);
                let s1 = setNum(seconds);

                //输出时分秒
                let fileName = year+mouth1+day1+h1+m1+s1;
                //设置函数 把小于10的数字转换为两位数
                function setNum(num){ return num < 10 ? '0' + num : num }
                return fileName;

            },
            getFormatTimeLine(nowTime){
                //获取一个现在的时间
                let year = nowTime.getFullYear();
                let mouth = nowTime.getMonth() + 1;
                let day =nowTime.getDate();
                let hour = nowTime.getHours();
                let minutes = nowTime.getMinutes();
                let seconds= nowTime.getSeconds();

                //将时分秒转化为双位数
                let mouth1 =setNum(mouth);
                let day1 =setNum(day);
                let h1 = setNum(hour);
                let m1 = setNum(minutes);
                let s1 = setNum(seconds);

                //输出时分秒
                let createTime = year+"-"+mouth1+"-"+day1+" "+h1+":"+m1+":"+s1;
                //设置函数 把小于10的数字转换为两位数

                function setNum(num){ return num < 10 ? '0' + num : num }
                return createTime;

            },
            sendStep(imageURL,nowTime){
                let that = this;
                let methodName = "确认";
                let note = '';
                that.$api.step(that.id,that.name,methodName,note).then((resp)=>{
                    if(resp.status === 200){
                        //let otherFailSendInfo = failSendInfo.filter(item=>item.UserId!==UserId);//其余的失败信息集合*/
                        console.log("重复拍摄确认成功");
                        /*that.$router.push({name:this.lineWorkUrl,params: {step:that.step,id:that.id}});*/
                        that.$router.push({name:'lineWorkSurePhoto',params: {lineWorkUrl:that.lineWorkUrl,step:that.step,id:that.id,name:that.name}});
                    }
                }).catch((error)=>{
                    alert("计划流程出错");
                    console.log(error);
                });
                that.sendPhoto(imageURL,nowTime);
            },
            addTaskToast() {
                window.plugins.toast.showWithOptions(
                    {
                        message: "后台上传中",
                        duration: "short", // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself.
                        position: "bottom",
                        addPixelsY: -40  // added a negative value to move it up a bit (default 0)
                    }
                );
            },
            sendPhotoFaileToast() {
                let that = this;
                window.plugins.toast.showWithOptions(
                    {
                        message: that.name+"照片上传失败",
                        duration: "short", // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself.
                        position: "bottom",
                        addPixelsY: -40  // added a negative value to move it up a bit (default 0)
                    },
                    function(){console.log('toast success: ')},
                    function(){console.log('toast error: ')}
                );
            },


        },
    }
</script>

